import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import axios from 'axios';
import http from '@/utils/http';

export const useUserStore = defineStore('user', () => {
  const currentUser = ref(null);
  const token = ref(localStorage.getItem('token') || '');
  const loading = ref(false);
  const error = ref(null);

  const isLoggedIn = computed(() => !!currentUser.value);
  const isAdmin = computed(() => currentUser.value?.userRole === 'admin');

  // 初始化用户信息
  const initUser = async () => {
    // 不再检查token，因为使用Session认证
    try {
      loading.value = true;
      // 使用正确的API路径，不再设置Authorization头
      const response = await http.get('/user/get/login');
      // response已经是后端返回的data部分，直接使用
      currentUser.value = response.data;
      // 如果成功获取用户信息，确保token也存在（保持兼容性）
      if (!token.value && currentUser.value) {
        token.value = 'session-auth';
        localStorage.setItem('token', token.value);
      }
    } catch (err) {
      console.error('Failed to fetch user info:', err);
      error.value = '获取用户信息失败';
      // 清除用户信息和token
      currentUser.value = null;
      token.value = '';
      localStorage.removeItem('token');
    } finally {
      loading.value = false;
    }
  };

  // 登录
  const login = async (userAccount, userPassword) => {
    try {
      loading.value = true;
      error.value = null;
      const response = await http.post('/user/login', {
        userAccount,
        userPassword
      });
      // http实例的响应拦截器已经处理了response.data，所以直接使用response
      const data = response.data;
      // 设置一个标记表示已登录（保持兼容性）
      token.value = 'session-auth';
      localStorage.setItem('token', token.value);
      // 设置当前用户信息
      currentUser.value = data;
      return true;
    } catch (err) {
      console.error('Login failed:', err);
      error.value = err.response?.data?.message || '登录失败，请检查账号和密码';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 注册
  const register = async (userAccount, userPassword, checkPassword) => {
    try {
      loading.value = true;
      error.value = null;
      const response = await http.post('/user/register', {
        userAccount,
        userPassword,
        checkPassword
      });
      return true;
    } catch (err) {
      console.error('Registration failed:', err);
      error.value = err.response?.data?.message || '注册失败，请稍后再试';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 登出
  const logout = async () => {
    try {
      // 调用后端的登出接口
      await http.post('/user/logout');
    } catch (err) {
      console.error('Logout error:', err);
    } finally {
      // 无论后端请求是否成功，都清除前端状态
      token.value = '';
      currentUser.value = null;
      localStorage.removeItem('token');
    }
  };

  return {
    currentUser,
    token,
    loading,
    error,
    isLoggedIn,
    isAdmin,
    initUser,
    login,
    register,
    logout
  };
});